<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>添加作业</title>

    <link href="/assets/images/favicon.ico" rel="icon">
    <link rel="stylesheet" href="/assets/libs/layui/css/layui.css" />
    <link rel="stylesheet" href="/assets/module/admin.css?v=318" />

    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript" src="/assets/libs/layui/layui.js"></script>
    <script type="text/javascript" src="/assets/js/common.js?v=318"></script>
    <style>
        .model-form-footer {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">

            <form class="layui-form model-form" id="homeworkForm" th:object="${model}">
                <input type="hidden" th:field="*{id}" />
                <!-- 班级选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">班级</label>
                    <div class="layui-input-block">
                        <select id="classSelect" name="classs" required th:attr="data-selected=${model.classs.className}" lay-filter="classSelect">
                            <option value="">请选择班级</option>
                        </select>
                    </div>
                </div>
                <!-- 开始时间 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-block">
                        <input type=type="datetime-local" th:field="*{beginDate}"
                               th:value="${#dates.format(model.beginDate, 'yyyy-MM-dd HH:mm:ss')}"
                               id="startTime" required lay-verify="required" placeholder="选择开始时间" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <!-- 结束时间 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-block">
                        <input type=type="datetime-local" th:field="*{endDate}"
                               th:value="${#dates.format(model.endDate, 'yyyy-MM-dd HH:mm:ss')}"
                               id="endTime" required lay-verify="required" placeholder="选择结束时间" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <!-- 项目选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">培训项目</label>
                    <div class="layui-input-block">
                        <select id="projectSelect" name="project" required th:attr="data-selected=${model.project.projectName}" lay-filter="projectSelect">
                            <option value="">请选择项目</option>
                        </select>
                    </div>
                </div>
                <!-- 类型选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-block">
                        <input type="text" name="homeworkType" required placeholder="类型" autocomplete="off" class="layui-input" th:value="${model.homeworkType}">
                    </div>
                </div>
                <!-- 作业内容 -->
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">作业内容</label>
                    <div class="layui-input-block">
                        <textarea th:field="*{title}" placeholder="请输入作业内容" class="layui-textarea" required lay-verify="required"></textarea>
                    </div>
                </div>
                <!-- 提交按钮 -->
                <div class="layui-form-item text-center model-form-footer">
                    <button class="layui-btn" lay-filter="save" lay-submit>发布</button>
                    <button type="button" class="layui-btn layui-btn-primary" lay-event="closeDialog">关闭</button>
                </div>
            </form>

            <script src="/assets/libs/jquery/jquery-3.2.1.min.js"></script>
            <script>
                $(function () {
                    layui.use(['form', 'layer', 'laydate'], function () {
                        var form = layui.form;
                        var layer = layui.layer;
                        var laydate = layui.laydate;
                        var $ = layui.jquery;
                        var studentNum
                        var userId
                        // 访问父窗口的数据
                        var classesNameList = parent.ClassNames
                        console.log('classesNameList:', classesNameList)
                        var projectNameList = parent.ProjectNames
                        console.log('projectNameList:', projectNameList)
                        var  chargerName=parent.chargerName
                        console.log(chargerName)
                        userId=chargerName
                        var index = parent.layer.getFrameIndex(window.name);
                        populateDropdowns()
                        function populateDropdowns() {
                            // 填充项目下拉菜单
                            var projectDropdown = $("#projectSelect");
                            var selectedProject = $("#projectSelect").data("selected"); // 获取回显值
                            console.log('selectedProjectId:', selectedProject);
                            projectDropdown.empty();
                            projectDropdown.append('<option value="">请选择项目</option>');
                            projectNameList.forEach(function (project) {
                                if (selectedProject === project){
                                    projectDropdown.append(new Option(project, project, true, true));
                                }else{
                                    projectDropdown.append( new Option(project, project));
                                }

                            });
                            // 填充班级下拉菜单
                            var classDropdown = $("#classSelect");
                            var selectedClassName = $("#classSelect").data("selected");
                            classDropdown.empty();
                            classDropdown.append('<option value="">请选择班级</option>');
                            console.log('selectedClassName:', selectedClassName);
                            classesNameList.forEach(function (classItem) {
                                if (selectedClassName === classItem){
                                    classDropdown.append(new Option(classItem, classItem, true, true));
                                }else{
                                    classDropdown.append(new Option(classItem, classItem));
                                }
                            });

                            layui.form.render('select'); // 更新layui表单渲染
                        }
                        form.on('select(classSelect)', function (data) {
                            console.log("班级监听")
                            var selectedClass = data.value;
                            console.log(selectedClass)
                            if (selectedClass) {
                                    loadProjectsByClass(selectedClass);
                            }
                            else{
                                populateDropdowns()
                            }
                        });
                        function loadProjectsByClass(className) {
                            $.ajax({
                             url: '/class/getProjectsByClass', // 根据班级获取项目
                               type: 'GET',
                                data: { class: className },
                                  success: function (data) {
                                   if (data && data.code === 0 && Array.isArray(data.data)) {
                                        var projectSelect = $('#projectSelect');
                                        projectSelect.empty();
                                        data.data.forEach(function (item) {
                                           projectSelect.append('<option value="' + item + '">' + item + '</option>');
                                       });
                                form.render('select');
                                  }
                               },
                                 error: function (xhr, status, error) {
                                    console.error("请求失败: " + status + ", " + error);
                                 }
                             });
                        }
                        // 格式化日期函数
                        function formatDate(dateStr) {
                            var date = new Date(dateStr);
                            var year = date.getFullYear();
                            var month = (date.getMonth() + 1).toString().padStart(2, '0');
                            var day = date.getDate().toString().padStart(2, '0');
                            var hour = date.getHours().toString().padStart(2, '0');
                            var minute = date.getMinutes().toString().padStart(2, '0');
                            var second = date.getSeconds().toString().padStart(2, '0');
                            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                        }

                        // 初始化日期输入框
                        $('#startTime').val(formatDate($('#startTime').val()));
                        $('#endTime').val(formatDate($('#endTime').val()));

                        laydate.render({
                            elem: '#startTime',
                            type: 'datetime',
                            format: 'yyyy-MM-dd HH:mm:ss'
                        });
                        laydate.render({
                            elem: '#endTime',
                            type: 'datetime',
                            format: 'yyyy-MM-dd HH:mm:ss'
                        });
                        // // Get the parent layer index
                        // var index = parent.layer.getFrameIndex(window.name);
                        // // // Auto-adjust iframe height
                        // parent.layer.iframeAuto(index);
                        function find() {
                            var class_selct = $("#classSelect").val();
                            $.ajax({
                                url: '/class/findClassNum?className=' + class_selct,
                                type: 'GET',
                                success: function (data) {
                                    if (data.code === 0) {
                                        studentNum = data.data;
                                        console.log(studentNum);
                                    } else {
                                        console.log(data.msg);
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error("请求失败: " + status + ", " + error);
                                }

                            });
                        }
                        function validateForm() {
                            // 获取表单元素的值
                            var project = $("#projectSelect").val();
                            var startTime = $("#startTime").val();
                            var endTime = $("#endTime").val();
                            var classs = $("#classSelect").val();
                            var homeworkType = $("input[name='homeworkType']").val();
                            var title = $("textarea[name='title']").val();
                            console.log(startTime)
                            // 检查项目是否选择
                            if (project === "") {
                                layer.msg("请选择项目", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            // 检查开始时间是否填写
                            if (startTime === "") {
                                layer.msg("请填写开始时间", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            // 检查结束时间是否填写
                            if (endTime === "") {
                                layer.msg("请填写结束时间", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            // 检查班级是否选择
                            if (classs === "") {
                                layer.msg("请选择班级", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            // 检查类型是否填写
                            if (homeworkType === "") {
                                layer.msg("请填写类型", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            // 检查作业内容是否填写
                            if (title === "") {
                                layer.msg("请填写作业内容", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            // 检查开始时间是否小于等于结束时间
                            var startDate = new Date(startTime);
                            var endDate = new Date(endTime);
                            if (startDate > endDate) {
                                layer.msg("开始时间不能晚于结束时间", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }

                            return true;
                        }
                        // Listen for form submission
                        form.on('submit(save)', function (data) {
                            // Show loading layer
                            var loadIndex = layer.load(2);
                            if (!validateForm()) {
                                layer.close(loadIndex);
                                return false;
                            }


                            find();


                            // 等待异步请求完成后再发送表单数据
                            var interval = setInterval(function () {
                                if (typeof studentNum!== 'undefined' && typeof userId!=='undefined') {
                                    clearInterval(interval);
                                    var formData = $("#homeworkForm").serializeArray();
                                    var beginDate = new Date($("#startTime").val()).toISOString();
                                    var endDate = new Date($("#endTime").val()).toISOString();
                                    formData.push({name: "beginDate", value: beginDate});
                                    formData.push({name: "endDate", value: endDate});
                                    console.log(JSON.stringify(formData))
                                    var formDataObj = {};
                                    formData.forEach(function (item) {
                                        // 排除项目名称，避免重复添加
                                        if (item.name!== $("#projectSelect").val()||item.name!== $("#classSelect").val()) {
                                            formDataObj[item.name] = item.value;
                                        }
                                    });
                                    formDataObj.studentNum = studentNum;
                                    formDataObj.userId = userId;
                                    formDataObj.project = {
                                        projectName: $("#projectSelect").val()
                                    };
                                    formDataObj.classs = {
                                        className: $("#classSelect").val()
                                    };
                                console.log(JSON.stringify(formDataObj))
                                    // Send AJAX request
                                    $.ajax({
                                        type: 'POST',
                                        url: "/homework/save",
                                        contentType: 'application/json',  // Set content type as JSON
                                        data: JSON.stringify(formDataObj), // Convert form data to JSON
                                        dataType: 'json',
                                        success: function (res) {
                                            layer.close(loadIndex);
                                            if (res.code === 0) {
                                                // Trigger parent window's search to refresh table
                                                $('#search', parent.document).click();
                                                // Close the current layer
                                                parent.layer.close(index);
                                                // Show success message
                                                parent.layer.msg('保存成功', {icon: 1});
                                            } else {
                                                layer.msg('保存失败: ' + res.msg, {icon: 2});
                                            }
                                        },
                                        error: function () {
                                            layer.close(loadIndex);
                                            layer.msg('网络错误，请稍后再试', {icon: 2});
                                        }
                                    });
                                }
                            }, 100);


                            return false; // Prevent form submission
                        });


                        // Handle close button click
                        $('.layui-btn-primary').on('click', function () {
                            parent.layer.close(index);
                        });
                    });
                });
            </script>

        </div>
    </div>
</div>

<footer>
    <!-- JS部分 -->
    <script type="text/javascript">
        var url = window.location.pathname.substring(1);
        var item = url.split("/");
        var jsUrl = "/static/module/javaweb_" + item[0] + ".js";
        document.write("<script src='" + jsUrl + "'><\/script>");
    </script>
</footer>
</body>
</html>